package com.weavernorth.action.paymentSlip;

import com.alibaba.fastjson.JSONObject;
import com.weavernorth.action.paymentSlip.pojo.messageVo;
import com.weavernorth.action.paymentSlip.utils.ApiSign;
import com.weavernorth.util.HttpUtil;
import com.weavernorth.util.Logger4jUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.wechat.util.Utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.weavernorth.util.dateUtils.getNowDateTime;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.action.paymentSlip.utils
 * @date: 2021/7/16 15:39
 * @description: 付款单确认接口：为预防客商融资后导致坏账风险，BPM 系统为客商提交付款申请时通过该接口校
 * 验客商在该核心企业下的账目总额必须大于等于在绒信平台的融资余额
 */
public class paymentSlip implements Action {
    /***
     * action主方法
     * @param requestInfo
     * @return
     */
    @Override
    public String execute(RequestInfo requestInfo) {
        Logger log = Logger4jUtil.getLoggerByName("/action/paymentSlip/");
        BaseBean bb=new BaseBean();
        log.info("付款单确认接口（BPM——>绒信平台）begin===>");
        //请求id
        String strRequestid = requestInfo.getRequestid();
        log.info("流程requestid="+strRequestid);
        String strTable = requestInfo.getRequestManager().getBillTableName();
        log.info("流程主表="+strTable);
        String strResponseBody = "";
        try {
            //根据requestid获取主表信息
            String strMain = " select * from " + strTable + " where requestid="+strRequestid;
            RecordSet rs = new RecordSet();
            rs.executeQuery(strMain);
            String payerCode = "";//付款单位统一社会信用代码
            String payeeCode = "";//收款单位统一社会信用代码
            String payerType = "";//付款方式
            String sfsjblyw="";//是否涉及保理业务
            BigDecimal amount = new BigDecimal("0.00");//付款金额
            Map<String, Object> map = new HashMap<>();
            while (rs.next()) {
                payerCode = Utils.null2String(rs.getString("fkgsshtyxydm"));
                log.info("付款单位统一社会信用代码：" + payerCode);
                payeeCode = Utils.null2String(rs.getString("gysshtyxydm"));
                sfsjblyw = Utils.null2String(rs.getString("sfsjblyw"));
                log.info("收款单位统一社会信用代码：" + payeeCode);
                payerType = Utils.null2String(rs.getString("fkfs"));
                log.info("付款方式：" + payerType);
                String str_amount="0.00";
                if(payerType.equals("0")){
                    str_amount=Util.null2String(rs.getString("bcfkhjy"),"0.00");//取付款金额
                }else{
                    str_amount=Util.null2String(rs.getString("bcyfkhjy"),"0.00");//取预付款金额
                }
                BigDecimal b_amount=new BigDecimal(str_amount);
                log.info("付款金额：" + b_amount.toString());//保留小数点后两位
                amount=amount.add(b_amount);
                map.put("payerCompanyCreditNo", payerCode);
                map.put("payeeCompanyCreditNo", payeeCode);
                map.put("amount", amount);
            }
            if(sfsjblyw.equals("0")) {
                String url = bb.getPropValue("payMentSlipProps", "url");
                log.info("绒信接口url地址=" + url);
                String appid = bb.getPropValue("payMentSlipProps", "app_id");

                String app_secret = bb.getPropValue("payMentSlipProps", "app_secret");
                log.info("app_secret=" + app_secret);
                String timestamp = getNowDateTime();//获取当前时间戳

                String str_token = ApiSign.fddParam(appid, timestamp, app_secret, map);

                //payerCompanyCreditNo=911506007901855983&payeeCompanyCreditNo=91340181556338349R&
                CloseableHttpClient client = HttpClients.createDefault();
                HttpUtil httpUtils = new HttpUtil();
                log.info("===传入参数===");
                log.info("sign=：" + str_token);
                log.info("timestamp=" + timestamp);
                log.info("appId=" + appid);
                log.info("amount=" + amount.toString());
                log.info("payerCompanyCreditNo=" + payerCode);
                log.info("payeeCompanyCreditNo=" + payeeCode);
                log.info("=========");
                HashMap<String, Object> params = new HashMap<>();
                params.put("sign", str_token);
                params.put("timestamp", timestamp);
                params.put("appId", appid);
                params.put("amount", amount.toString());
                params.put("payerCompanyCreditNo", payerCode);
                params.put("payeeCompanyCreditNo", payeeCode);
                //contentType:application/x-www-form-urlencoded
                strResponseBody = httpUtils.sendPost(url,params, log);
                log.info("返回结果:" + strResponseBody);
                JSONObject jsonResult = JSONObject.parseObject(strResponseBody);
                messageVo resultMessage = JSONObject.toJavaObject(jsonResult, messageVo.class);
                log.info("返回结果转为对象格式化：" + resultMessage.toString());
                if (resultMessage.getResp_code().equals("200")) {
                    log.info("付款单确认接口（BPM——>绒信平台）end===");
                    if(!resultMessage.getData().getStatus().equals("1")){
                        requestInfo.getRequestManager().setMessagecontent(resultMessage.getData().getRemarks());
                        return FAILURE_AND_CONTINUE;
                    }

                } else {
                    requestInfo.getRequestManager().setMessagecontent(resultMessage.getData().getRemarks());
                    return FAILURE_AND_CONTINUE;
                }
            }
        }catch (Exception ex){
            log.info("程序异常，异常信息："+ex.toString());
            log.info("付款单确认接口（BPM——>绒信平台）end===");
            requestInfo.getRequestManager().setMessagecontent(ex.toString());
            return FAILURE_AND_CONTINUE;
        }
        log.info("付款单确认接口（BPM——>绒信平台）end===");
        return SUCCESS;
    }
}
